package cn.skcks.springboot04data.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JdbcController {

	private JdbcTemplate jdbcTemplate;
	@Autowired
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		System.out.println("jdbcTemplate 注入");
		this.jdbcTemplate = jdbcTemplate;
	}

	// 查询数据库的所有信息
	@RequestMapping("/userList")
	public List<Map<String, Object>> userList() {
		System.out.println("访问 => /user");
		String sql = "SELECT id,name,pwd FROM user";
		return jdbcTemplate.queryForList(sql);
	}

	@RequestMapping("/addUser")
	public String addUser() {
		String sql = "INSERT INTO user(id,name,pwd) VALUE (1000,'SpringBoot','12341234')";
		try {
			jdbcTemplate.update(sql);
			return "插入成功";
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return "插入失败";
		}
	}

	@RequestMapping("/updateUser")
	public String updateUser() {
		String sql = "UPDATE user SET pwd = ? WHERE id=?";
		try {
			jdbcTemplate.update(sql, 43214321, 1000);
			return "更新成功";
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return "更新失败";
		}
	}

	@RequestMapping("/deleteUser/{id}")
	public String deleteUser(@PathVariable("id") int id) {
		String sql = "DELETE FROM user WHERE id=?";
		try {
			jdbcTemplate.update(sql, id);
			return "删除成功";
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return "删除失败";
		}
	}
}